//
//  TwoViewController.m
//  Study1
//
//  Created by ChenJie on 2/7/20.
//  Copyright © 2020 OrgName. All rights reserved.
//

#import "TwoViewController.h"
#import <MJRefresh/MJRefresh.h>
#import <MBProgressHUD/MBProgressHUD.h>
#import "SectionHeaderView.h"
#import "SectionFooterView.h"
#import "TableHeaderView.h"
#import "TableFooterView.h"
#import "ACell.h"
#import "UIView+name.h"
#import "WeiboService.h"

typedef NS_ENUM(NSUInteger, kLoadDataType) {
    kLoadDataType_reload = 1,
    kLoadDataType_loadMore,
};

@interface TwoViewController ()
<
UITableViewDataSource,
UITableViewDelegate,
ACellDelegate
>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) TableHeaderView *tableHeaderView;
@property (nonatomic, strong) TableFooterView *tableFooterView;
@property (nonatomic, strong) UIBarButtonItem *closeButtonItem;
@property (nonatomic, strong) UIBarButtonItem *addButtonItem;
@property (nonatomic, strong) UIBarButtonItem *deleteButtonItem;
//@property (nonatomic, strong) NSMutableArray *allLayouts;
@property (nonatomic, strong) NSMutableArray *dataList;
@property (nonatomic, strong) WeiboService *service;
@property (nonatomic, assign) NSInteger pageIndex;

@end

@implementation TwoViewController

#pragma mark - ViewController lifecycle

- (instancetype)init {
    self = [super init];
    if (self) {
        [self initDataSource];
        self.pageIndex = 1;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //
    self.view.backgroundColor = [UIColor lightGrayColor];
    self.navigationItem.title = @"TableView";
    
//    self.navigationItem.rightBarButtonItem = self.closeButtonItem;
    self.navigationItem.rightBarButtonItems = @[self.addButtonItem, self.closeButtonItem];
    
    self.navigationItem.leftBarButtonItem = self.deleteButtonItem;
    
    //
    [self.view addSubview:self.tableView];
    
    [self.tableView.mj_header beginRefreshing];
    
//    [self doIt];
//    NSString *selectName = @"doIt";
//    [self performSelector:NSSelectorFromString(selectName)];
    
    
//    self.tableView.editing = YES;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    //
    self.tableView.frame = self.view.bounds;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

#pragma mark - Public methods



#pragma mark - Private methods

- (void)initDataSource {
//    for (NSInteger i = 0; i < 10; i++) {
//        [self.allLayouts addObject:[NSMutableDictionary dictionary]];
//    }
    
//    for (NSInteger i = 0; i < 10; i++) {
//        ACellVM *cellViewModel = [ACellVM new];
//
//        cellViewModel.iconImage = [UIImage imageNamed:@"1"];
//        cellViewModel.title = @"三大运营商可查个人轨迹 30天内去过哪里一目了然";
//        cellViewModel.content = @"最近很多人已经开工了，但是由于众所周知的方法，多个城市都是要严查某些省市的人员的，如何证明自己之前去或者没去过那些敏感地区？这是个难题，现在可以借助运营商的漫游查询来证明个人轨迹了。日前有多位网友在网上分享了一份《个人轨迹证明方法》的说明，手机用户可以发送短信给运营商，授权之后查询15天到30天内手机漫游过的地区，大V@弗虑弗为验证之后可用。";
//
//        [self.dataList addObject:cellViewModel];
//    }
    
    
//    ACellVM *cellViewModel = [ACellVM new];
//    cellViewModel.iconImage = [UIImage imageNamed:@"1"];
//    cellViewModel.title = @"三大运营商可查个人轨迹 30天内去过哪里一目了然";
//    cellViewModel.content = @"最近很多人已经开工了，但是由于众所周知的方法，多个城市都是要严查某些省市的人员的，如何证明自己之前去或者没去过那些敏感地区？这是个难题，现在可以借助运营商的漫游查询来证明个人轨迹了。日前有多位网友在网上分享了一份《个人轨迹证明方法》的说明，手机用户可以发送短信给运营商，授权之后查询15天到30天内手机漫游过的地区，大V@弗虑弗为验证之后可用。";
//    [self.dataList addObject:cellViewModel];
    
    
    
//    [self addRowWithImageName:@"1" title:@"三大运营商可查个人轨迹 30天内去过哪里一目了然" content:@"最近很多人已经开工了，但是由于众所周知的方法，多个城市都是要严查某些省市的人"];
//    [self addRowWithImageName:@"2"
//                        title:@"商返回出来的漫游信息，这个短信在需要的时候可以出示，但移动表示此业务为公益服务，查询结果仅供参考，不作为最终判定依据。"
//                      content:@"编写CXMYD,发送到10086,再依据回复短信输入身份证后四位，可查询过去一个月内去过的省和直辖市(无地市)。"];
//    [self addRowWithImageName:@"3" title:@"1111移动用户证明方法" content:@"手机发送:“CXMYD#身份证后四"];
//    [self addRowWithImageName:@"3" title:@"222移动用户证明方法" content:@"手机发送:“CXMYD#身份证后四"];
//    [self addRowWithImageName:@"3" title:@"333移动用户证明方法" content:@"手机发送:“CXMYD#身份证后四"];
//    [self addRowWithImageName:@"3" title:@"444移动用户证明方法" content:@"手机发送:“CXMYD#身份证后四"];
//    [self addRowWithImageName:@"3" title:@"555移动用户证明方法" content:@"手机发送:“CXMYD#身份证后四"];
//    [self addRowWithImageName:@"3" title:@"666移动用户证明方法" content:@"手机发送:“CXMYD#身份证后四"];
//    [self addRowWithImageName:@"3" title:@"777移动用户证明方法" content:@"手机发送:“CXMYD#身份证后四"];
//    [self addRowWithImageName:@"3" title:@"888移动用户证明方法" content:@"手机发送:“CXMYD#身份证后四"];
//    [self addRowWithImageName:@"3" title:@"999移动用户证明方法" content:@"手机发送:“CXMYD#身份证后四"];
//    [self addRowWithImageName:@"3" title:@"00000移动用户证明方法" content:@"手机发送:“CXMYD#身份证后四"];
//    [self addRowWithImageName:@"3" title:@"33335s移动用户证明方法" content:@"手机发送:“CXMYD#身份证后四"];
//    [self addRowWithImageName:@"3" title:@"111移动用户证明方法" content:@"手机发送:“CXMYD#身份证后四"];
//    [self addRowWithImageName:@"3" title:@"22移动用户证明方法" content:@"手机发送:“CXMYD#身份证后四"];
//
//
//    [self addRowWithImageName:@"4" title:@"" content:@""];
//    [self addRowWithImageName:@"5" title:@"" content:@""];
//    [self addRowWithImageName:@"1" title:@"" content:@""];
//    [self addRowWithImageName:@"1" title:@"" content:@""];
//    [self addRowWithImageName:@"1" title:@"" content:@""];
//    [self addRowWithImageName:@"1" title:@"" content:@""];
//    [self addRowWithImageName:@"1" title:@"" content:@""];
//    [self addRowWithImageName:@"1" title:@"" content:@""];
//    [self addRowWithImageName:@"1" title:@"" content:@""];
//    [self addRowWithImageName:@"1" title:@"" content:@""];
//    [self addRowWithImageName:@"1" title:@"" content:@""];
//    [self addRowWithImageName:@"1" title:@"" content:@""];
    
}

- (void)fetchDatasWithLoadDataType:(kLoadDataType)loadDataType {
    
    if (loadDataType == kLoadDataType_reload) {
        self.pageIndex = 1;
    }
    
    MBProgressHUD *hud =  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = @"Loading...";
    
    [self.service publicTimelineWithPageSize:kPageSize pageIndex:self.pageIndex success:^(NSArray * _Nonnull messageList) {
        
        [hud hideAnimated:YES];
        
        if (loadDataType == kLoadDataType_reload) { // 下拉
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer resetNoMoreData];
        } else { // 上拉，分两种情况，已经全部加载完成/还有更多数据
            if (messageList.count < kPageSize) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            } else {
                [self.tableView.mj_footer endRefreshing];
            }
        }
        
        self.pageIndex ++;
        NSArray *vmList = [self ACellVMListWithMessageList:messageList];
        if (loadDataType == kLoadDataType_reload) {
            [self.dataList removeAllObjects];
        }
        [self.dataList addObjectsFromArray:vmList];
        
        [self.tableView reloadData];
//        NSLog(@"success with response: %@", messageList);
        
    } failure:^(NSError * _Nonnull error) {
//        NSLog(@"fail with error: %@", error);
        
        hud.label.text = error.debugDescription;
        [hud hideAnimated:YES afterDelay:3];
        
        if (loadDataType == kLoadDataType_reload) {
            [self.tableView.mj_header endRefreshing];
        } else {
            [self.tableView.mj_footer endRefreshing];
        }
        
    }];
    
}

- (NSArray *)ACellVMListWithMessageList:(NSArray *)messageList {
    NSMutableArray *vmList = [NSMutableArray array];

    for (NSDictionary *messageInfo in messageList) {
        NSDictionary *userInfo = messageInfo[@"user"];
        NSString *username = userInfo[@"name"];
        NSString *userImageUrl = userInfo[@"profile_image_url"];
        NSString *content = messageInfo[@"text"];
        
        ACellVM *cellViewModel = [ACellVM new];
        cellViewModel.title = username;
        cellViewModel.content = content;
        cellViewModel.iconUrlString = userImageUrl;
        [vmList addObject:cellViewModel];
    }

    return vmList;
}

- (void)addRowWithImageName:(NSString *)imageName title:(NSString *)title content:(NSString *)content {
    [self addRowWithImage:[UIImage imageNamed:imageName] title:title content:content];
}

- (void)addRowWithImage:(UIImage *)image title:(NSString *)title content:(NSString *)content {
    
    ACellVM *cellViewModel = [ACellVM new];
    cellViewModel.iconImage = image;
    cellViewModel.title = title;
    cellViewModel.content = content;
    [self.dataList addObject:cellViewModel];
    
}

- (void)insertRowWithImageName:(NSString *)imageName title:(NSString *)title content:(NSString *)content {
    [self insertRowWithImage:[UIImage imageNamed:imageName] title:title content:content];
}

- (void)insertRowWithImage:(UIImage *)image title:(NSString *)title content:(NSString *)content {
    
    ACellVM *cellViewModel = [ACellVM new];
    cellViewModel.iconImage = image;
    cellViewModel.title = title;
    cellViewModel.content = content;
    [self.dataList insertObject:cellViewModel atIndex:0];
}

- (void)deleteRowAtIndex:(NSInteger)index {
    
    if (self.dataList.count <= index) {
        return;
    }
        
    [self.dataList removeObjectAtIndex:index];
    
    //
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
    [self.tableView deleteRowsAtIndexPaths:@[indexPath]
                          withRowAnimation:UITableViewRowAnimationNone];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

    });
    
//    [self.tableView reloadData];
    
}

- (void)refreshDatas {
    [self fetchDatasWithLoadDataType:kLoadDataType_reload];
}

- (void)loadMoreDatas {
    [self fetchDatasWithLoadDataType:kLoadDataType_loadMore];
}

#pragma mark - Event response methods

- (void)buttonClicked:(UIButton *)button {
    NSLog(@"button clicked...");
}

- (void)closeIt:(UIBarButtonItem *)buttonItem {
    NSLog(@"now close..");
    
//    [self dismissViewControllerAnimated:YES completion:^{
//    }];
    
    self.tableView.editing = !self.tableView.isEditing;
    
}

- (void)addRow:(UIBarButtonItem *)buttonItem {
    NSLog(@"now add..");
    
    //
    [self insertRowWithImageName:@"4" title:@"444444" content:@"22222222"];
    
    //
    NSIndexPath *rowIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView insertRowsAtIndexPaths:@[rowIndexPath]
                          withRowAnimation:UITableViewRowAnimationAutomatic];
    
}

- (void)deleteRow:(UIBarButtonItem *)buttonItem {
    
    [self deleteRowAtIndex:0];
}

#pragma mark - Deletate methods



#pragma mark - <UITableViewDataSource>

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataList.count;
}

//#define kIconImage [UIImage imageNamed:@"1"]
//#define kTitle @"三大运营商可查个人轨迹 30天内去过哪里一目了然"
//#define kContent @"最近很多人已经开工了，但是由于众所周知的方法，多个城市都是要严查某些省市的人员的，如何证明自己之前去或者没去过那些敏感地区？这是个难题，现在可以借助运营商的漫游查询来证明个人轨迹了。日前有多位网友在网上分享了一份《个人轨迹证明方法》的说明，手机用户可以发送短信给运营商，授权之后查询15天到30天内手机漫游过的地区，大V@弗虑弗为验证之后可用。"

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
//    NSLog(@"cell for row: %@", indexPath);
    
    NSString *identifier = @"cell";
    ACell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[ACell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.delegate = self;
    }
//    cell.textLabel.text = [NSString stringWithFormat:@"section:%ld, row:%ld", (long)indexPath.section, (long)indexPath.row];
//    cell.imageView.image = [UIImage imageNamed:@"1"];
//    cell.detailTextLabel.text = [NSString stringWithFormat:@"sub:%ld, row:%ld", (long)indexPath.section, (long)indexPath.row];
    
//    cell.iconImage = kIconImage;
//    cell.title = kTitle;
//    cell.content = kContent;
//    cell.layouts = self.allLayouts[indexPath.row];
    
    cell.viewModel = self.dataList[indexPath.row];
    cell.indexPath = indexPath;
    
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
//    return [NSString stringWithFormat:@"section header: %ld", (long)section];
//}
//
//- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
//    return [NSString stringWithFormat:@"section footer: %ld", (long)section];
//}

#pragma mark - <UITableViewDelegate>

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    NSLog(@"index path: %@", indexPath);
    
//    ACell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
//    NSMutableDictionary *layouts = self.allLayouts[indexPath.row];
//    if (!layouts) {
//        layouts = [NSMutableDictionary dictionary];
//        self.allLayouts[indexPath.row] = layouts;
//    }
//
//    return [ACell cellHeightWithIconImage:kIconImage title:kTitle content:kContent layouts:layouts];
    
    
    ACellVM *viewModel = self.dataList[indexPath.row];
    return [ACell cellHeightWithCellModel:viewModel];
}

//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
//    SectionHeaderView *headerView = [SectionHeaderView new];
//    headerView.sectionIndex = section;
//    return headerView;
//}
//
//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
//    SectionFooterView *footerView = [SectionFooterView new];
//    footerView.sectionIndex = section;
//    return footerView;
//}

//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
//    return 20;
//}
//
//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
//    return 20;
//}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"now select..");
    
//    TwoViewController *vc = [[TwoViewController alloc] init];
//    vc.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:vc animated:YES];
    
//    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
//
//    [self presentViewController:nav animated:YES completion:^{
//    }];
    
//    [self deleteRowAtIndex:indexPath.row];
    
    
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"abc";
}

-   (void)tableView:(UITableView *)tableView
 commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
  forRowAtIndexPath:(NSIndexPath *)indexPath {

//
//    if (self.dataList.count <= indexPath.row) {
//        return;
//    }
//    [self.dataList removeObjectAtIndex:indexPath.row];
//
//    //
//    [self.tableView deleteRowsAtIndexPaths:@[indexPath]
//                          withRowAnimation:UITableViewRowAnimationLeft];
    
    
    [self deleteRowAtIndex:indexPath.row];
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

-   (void)tableView:(UITableView *)tableView
 moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath
        toIndexPath:(NSIndexPath *)destinationIndexPath {
    
    NSLog(@"11");
}

#pragma mark - <ACellDelegate>

- (void)cell:(ACell *)cell iconDidClick:(UIView *)iconView {
//    NSLog(@"now click...");
    
    
    // 方案1: 获取当前 viewmodel 在 dataList 中的 index，作为 cellIndex
//    ACellVM *viewModel = cell.viewModel;
//    NSInteger cellIndex = [self.dataList indexOfObject:viewModel];
//    [self deleteRowAtIndex:cellIndex];
    
    [iconView callMyName];
    
    // 方案2: 每次 delete 之后，遍历 dataList，为 viewModel.indexPath 重新赋值
    
    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [self.tableView reloadData];
//    });
    
}

#pragma mark - Setter



#pragma mark - Getter

- (UITableView *)tableView {
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        tableView.dataSource = self;
        tableView.delegate = self;
//        tableView.tableHeaderView = self.tableHeaderView;
//        tableView.tableFooterView = self.tableFooterView;
        tableView.estimatedRowHeight = 0;
        
        tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self
                                                               refreshingAction:@selector(refreshDatas)];
        
        tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self
                                                                   refreshingAction:@selector(loadMoreDatas)] ;
        
        _tableView = tableView;
    }
    return _tableView;
}

- (TableHeaderView *)tableHeaderView {
    if (!_tableHeaderView) {
        TableHeaderView *view = [TableHeaderView new];
        view.frame = CGRectMake(0, 0, 10, 44);
        view.clipsToBounds = YES;
        
        _tableHeaderView = view;
    }
    return _tableHeaderView;
}

- (TableFooterView *)tableFooterView {
    if (!_tableFooterView) {
        TableFooterView *view = [TableFooterView new];
        view.frame = CGRectMake(0, 0, 0, 100);
        
        _tableFooterView = view;
    }
    return _tableFooterView;
}

- (UIBarButtonItem *)closeButtonItem {
    if (!_closeButtonItem) {
        UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
                                                                                    target:self
                                                                                    action:@selector(closeIt:)];
        _closeButtonItem = buttonItem;
    }
    return _closeButtonItem;
}

- (UIBarButtonItem *)addButtonItem {
    if (!_addButtonItem) {
        UIBarButtonItem *buttonItem
        = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                                                        target:self
                                                        action:@selector(addRow:)];
        _addButtonItem = buttonItem;
    }
    return _addButtonItem;
}

- (UIBarButtonItem *)deleteButtonItem {
    if (!_deleteButtonItem) {
        UIBarButtonItem *buttonItem
        = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash
                                                        target:self
                                                        action:@selector(deleteRow:)];
        _deleteButtonItem = buttonItem;
    }
    return _deleteButtonItem;
}

//- (NSMutableArray *)allLayouts {
//    if (!_allLayouts) {
//        _allLayouts = [NSMutableArray array];
//    }
//    return _allLayouts;
//}

- (NSMutableArray *)dataList {
    if (!_dataList) {
        _dataList = [NSMutableArray array];
    }
    return _dataList;
}

- (WeiboService *)service {
    if (!_service) {
        WeiboService *service = [WeiboService new];
        _service = service;
    }
    return _service;
}

#pragma mark - Memory management

- (void)dealloc {
}

@end
